package SV_HASH_NO_SALT;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

public class Fixed {
    /*
     * Adds a new user; stores login and "salt:hash".
     */
    public void addUser(String login, byte[] password) {
        try {
            byte[] salt = new byte[16];
            Random secureRandom = new Random();
            secureRandom.nextBytes(salt);
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(salt); // use random salt
            md.update(password); // and password
            byte[] hash = md.digest();
            storeHashString(login, Hex.encodeHexString(salt) + ":" + Hex.encodeHexString(hash));
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalStateException(e);
        }
    }

    private void storeHashString(String login, String s) {
    }

    /*
     * Validates user login information. Returns true if user exists, and
       entered password matches stored "salt:hash"; otherwise returns false.
     */
    public boolean login(String login, byte[] password) {
        try {
            String storedSaltAndHash = readHashString(login);
            if (storedSaltAndHash != null) {
                String[] saltAndHash = storedSaltAndHash.split(":");
                if (saltAndHash.length != 2) {
                    throw new IllegalStateException("Expected salt:hash string");
                }
                MessageDigest md = MessageDigest.getInstance("MD5");
                md.update(Hex.decodeHex(saltAndHash[0].toCharArray())); // use stored salt
                md.update(password);
                byte[] hash = md.digest();
                return MessageDigest.isEqual(hash, Hex.decodeHex(saltAndHash[1].toCharArray()));
            } else {
                return false;
            }
        } catch (NoSuchAlgorithmException | DecoderException e) {
            throw new IllegalStateException(e);
        }
    }

    private String readHashString(String login) {
        return "";
    }
}
